#include<iostream>
using namespace std;


struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};
 
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == nullptr || head->next == nullptr) return head;
        ListNode* root = new ListNode(-1, head);
        int nodeCount = 0;
        ListNode* pcur = head;

        ListNode* pcurHead = head;
        ListNode* pcurTail = nullptr;

        while (pcur != nullptr) {
            nodeCount++;
            if (pcur->next == nullptr) {
                pcurTail = pcur;
            }
            pcur = pcur->next;
        }
        int newk = nodeCount - k % nodeCount;

        for (int i = 0; i < newk; i++) {
            root->next = pcurHead->next;
            pcurTail->next = pcurHead;
            pcurHead->next = nullptr;
            pcurTail = pcurTail->next;
            pcurHead = root->next;
        }
        head = root->next;
        return head;
    }
};